<?php
namespace Modules\Activity\Http\Controllers\Admin\Seckill;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use \Modules\Activity\Entities\Seckill\Activity;
// use \Modules\Activity\Entities\ActivityRecord;

use Validator;
use ThrowException;
use DB;

class ActivityController extends Controller
{
    public function index(Request $req)
    {
        $rule = [
            // 'type' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $options = $req->all();

        $options['order_by'] = ['list_weight' => 'desc'];
        // $options['with_count'] = ['records', 'skus'];
        // $options['with'] = ['activity_info'];

        $list = Activity::getList($options);

        return $list->generateListResponse();
    }

    public function show(Request $req, $uuid)
    {
        // 
        $item = Activity::getEntity([
            'uuid' => $uuid
        ]);

        $info = $item->getInfo();

        return [
            'info' => $info
        ];
    }

    public function store(Request $req)
    {
        $rule = [
            'start_at' => ['required'],
            'end_at' => ['required'],
            'thumb' => ['required'],
            'title' => ['required'],
            'node_id' => ['required'],
            'node_type' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $info = $req->all();

        $class = config('map.node_type')[$req->node_type];
        $node = $class::getEntity([
            'id' => $req->node_id
        ]);

        $info['node_uuid'] = $node->uuid;

        DB::beginTransaction();

        $item = Activity::create($info);

        DB::commit();

        return [
            'id' => $item->id,
            'uuid' => $item->uuid
        ];
    }

    public function update(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = Activity::getEntity([
            'uuid' => $uuid
        ]);

        DB::beginTransaction();

        if ($req->type === 'update') {
            $info = $req->input('attributes');

            if (@$info['node_type']) {
	            $class = config('map.node_type')[$info['node_type']];
	            $node = $class::getEntity([
	                'id' => $info['node_id']
	            ]);
	            $info['node_uuid'] = $node->uuid;
            }

            $item->update($info);
        }
        if ($req->type === 'copy') {
            $item->copy();
        }


        DB::commit();

        return [];
    }

    public function destroy(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = Activity::getEntity([
            'uuid' => $uuid
        ]);

        $item->delete();

        return [];
    }

}
